import java.util.PriorityQueue;

public class MyTimer {
    private Thread t;
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    private Object locker = new Object();
    public MyTimer(){
        //定时器构造方法的主体就是启动线程，让它去扫描队首元素
        t = new Thread(() -> {
            while (true) {
                synchronized (locker) {
                    while (queue.isEmpty()) {
                        try {
                            locker.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    MyTimerTask task = queue.peek();
                    long curTime = System.currentTimeMillis();
                    if (curTime >= task.getTime()) { //时间到了，执行任务
                        task.run();
                        queue.poll(); //记得执行后把它出队列
                    } else {
                        try {
                            locker.wait(task.getTime() - curTime); //如果还没到执行时间，那就等待，不要一直循环下去
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        });
        t.start();
    }

    public void schedule(Runnable runnable,long delay) { //把任务添加到 queue 里面
        synchronized (locker) {
            MyTimerTask task = new MyTimerTask(runnable, delay);
            queue.offer(task);
            locker.notify(); //添加元素后，就可以唤醒处于 wait 状态的线程
        }
    }

    public void cancel() {
        t.interrupt();
    }
}
